package com.aoip.telemetry.telemetry.test;

import com.aoip.telemetry.telemetry.core.crc.SnStCrcUtil;
import com.aoip.telemetry.telemetry.core.redis.RedisCache;
import com.aoip.telemetry.telemetry.entity.constant.TelemetryConstants;
import com.aoip.telemetry.telemetry.entity.enums.CacheKeyEnum;
import com.aoip.telemetry.telemetry.entity.equipment.StOnlineStatusEntity;
import com.aoip.telemetry.telemetry.mq.rabbitmq.SendMsgToRabbitMq;
import com.aoip.telemetry.telemetry.receive.session.Session;
import com.aoip.telemetry.telemetry.receive.session.SessionFactory;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.net.InetSocketAddress;
import java.time.LocalDateTime;

/**
 * @author chenbai
 * @version 1.0
 * @date 2022/2/23 21:03
 */
@Component
@Slf4j
public class UdpServerHandler extends SimpleChannelInboundHandler<String> {

    private static UdpServerHandler udpServerHandler;

    @Resource
    private RedisCache redisCache;
    @Resource
    private SendMsgToRabbitMq sendMsgToMq;

    @PostConstruct
    public void init() {
        udpServerHandler = this;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String originalMessage) {
//        ByteBuf buf = packet.copy().content();
//        byte[] req = new byte[buf.readableBytes()];
//        buf.readBytes(req);
//        String originalMessage = new String(req);

        int length = originalMessage.length();
        if (length == 18) {
//            心跳包
            return;
        }
        log.error("接收报文：{}", originalMessage);
//        Channel channel = ctx.channel();
//        InetSocketAddress inSocket = (InetSocketAddress) channel.localAddress();
//        StOnlineStatusEntity entity = new StOnlineStatusEntity();
//        String stCode = originalMessage.substring(3, 8);
//        entity.setStCode(stCode);
//        entity.setOnlineStatus(TelemetryConstants.ONLINE);
//        entity.setCommunicateIpPort(inSocket.getHostName() + ":" + inSocket.getPort());
//        entity.setOnlineTime(LocalDateTime.now());
//        udpServerHandler.mapper.insert(entity);
//        udpServerHandler.sendMsgToMq.sendMsg("exchange_telemetry_msg", "router_key_telemetry_hydrology", originalMessage);

        StringBuilder sb = new StringBuilder();
        String stCode = originalMessage.substring(0, 13);
        sb.append(stCode);
        sb.append(" DC ");
        int dc = originalMessage.indexOf("DC ");
        if (dc < 0) {
            return;
        }
        String num = originalMessage.substring(dc + 3, length - 5);
        String frameString = sb.append(num).append(" OK ").toString();
        String cs = SnStCrcUtil.crc(frameString);
        String str = frameString + cs + "NN";
        Channel channel = ctx.channel();
        ByteBuf heapBuffer = channel.alloc().heapBuffer();
        heapBuffer.writeBytes(str.getBytes());
        test(originalMessage, ctx);
//        DatagramPacket packet = new DatagramPacket()
//        DatagramPacket sendPacket = new DatagramPacket(heapBuffer, packet.sender());
//        ctx.writeAndFlush(sendPacket);
//        channel.writeAndFlush(heapBuffer);
//        ctx.writeAndFlush(heapBuffer);

    }

    private void test(String msg,ChannelHandlerContext ctx){
        System.out.println("msg" + msg);
        String stCodeIndexRange = "3,13";
        if (!StringUtils.hasText(stCodeIndexRange) || !stCodeIndexRange.contains(",")) {
            return;
        }
//        if (!firstConn) {
//            return;
//        }
        String[] range = stCodeIndexRange.split(",");
        int begin = Integer.valueOf(range[0]);
        int end = Integer.parseInt(range[1]);
        String s = msg.toString();
        if (s.length() < end) {
            return;
        }
        String stCode = s.substring(begin, end);
        Session session = SessionFactory.getSession();
        Channel channel = ctx.channel();
        session.bind(channel, stCode);
        channel.localAddress();
        InetSocketAddress inSocket = (InetSocketAddress) channel.localAddress();
        StOnlineStatusEntity entity = new StOnlineStatusEntity();
        entity.setStCode(stCode);
        entity.setOnlineStatus(TelemetryConstants.ONLINE);
        entity.setCommunicateIpPort(inSocket.getPort());
        entity.setOnlineTime(LocalDateTime.now());
        String key = CacheKeyEnum.STATION_ONLINE_STATUS + ":" + stCode;
        udpServerHandler.redisCache.deleteObject(key);
        udpServerHandler.redisCache.setCacheObject(key, entity);
//        bindStationAddressHandle.mapper.insert(entity);
//        firstConn = !firstConn;
//        session.setAttribute(channel, "id", entity.getId());
    }
}
